﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace NFinal.Middleware.Static
{
    /// <summary>
    /// Http中间件泛型类
    /// </summary>
    /// <typeparam name="TContext">Context或Environment等</typeparam>
    /// <typeparam name="TRequest">Request或IOwinContext等</typeparam>
    public abstract class Middleware<TContext, TRequest> : NFinal.Middleware.IMiddleware<TContext, TRequest>
    {
        /// <summary>
        /// 管道中下一个Http上下文处理函数
        /// </summary>
        public readonly InvokeDelegate<TContext> _next;
        private NFinal.Cache.ICacheT<string,Response> cache;
        /// <summary>
        /// 
        /// </summary>
        public Middleware(InvokeDelegate<TContext> next)
        {
            this._next = next;
        }
        /// <summary>
        /// 获取请求Url
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public abstract string GetRequestPath(TContext context);

        public abstract Request GetRequest(TContext context);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Invoke(TContext context)
        {
            cache = NFinal.Config.Configration.serviceCollection.GetService<NFinal.Cache.ICacheT<string, Response>>();
            string url = GetRequestPath(context);
            Request request = GetRequest(context);
            Response response = null;
            //string GetPrefix = Url();
            if (cache.TryGetValue(url, out response))
            {
                if (response.expires >= DateTime.Now)
                {
                    return InvokeAsync();
                }
            }
            return null;
        }
        public async Task InvokeAsync()
        {
            Stream stream = new MemoryStream();
            byte[] buffer = new byte[3];
            await stream.WriteAsync(buffer, 0, buffer.Length);
            await stream.WriteAsync(buffer, 0, buffer.Length);
            stream.Dispose();
        }
    }
}
